#include <iostream>
#include <signal.h>
#include "oj_control.hpp"
#include "../comm/httplib.h"
//进行服务路由功能
using namespace httplib;
using namespace ns_control;

static Control* ctl_ptr = nullptr;

void Recovery(int signum)
{
    ctl_ptr->RecoveryMachine();
}


int main()
{
    signal(SIGQUIT,Recovery);
    Server svr;
    Control ctl;
    ctl_ptr = &ctl;
    //获取所有题目
    svr.Get("/all_questions",[&ctl](const Request& Req, Response& Resp){
        std::string html;
        ctl.AllQuestions(&html);
        Resp.set_content(html,"text/html;charset=utf-8");
    });

    //用户根据题号获取特定的一道题
    svr.Get(R"(/question/(\d+))",[&ctl](const Request& Req, Response& Resp){
        std::string number = Req.matches[1];
        std::string html;
        ctl.Onequestion(number,&html);
        //ctl.Question(number,&html);
        Resp.set_content(html,"text/html;charset=utf-8");

    });


    //用户提交代码，使用我们的判题功能。(1. 每道题的测试用例 2. compile_and_run)
    svr.Post(R"(/judge/(\d+))",[&ctl](const Request& Req, Response& Resp){
        std::string number = Req.matches[1];
        std::string in_json = Req.body;
        //std::cout << in_json <<std::endl;
        std::string out_json;
        ctl.Judge(number,in_json,&out_json);
        Resp.set_content(out_json, "application/json;charset=utf-8");
        // resp.set_content("指定题目的判题: " + number, "text/plain; charset=utf-8");

    });
    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0",8080);

    return 0;
}